import Taro from '@tarojs/taro'
import '@tarojs/async-await'
import SettingUtils from './dto/settingUtils';

type HttpMethods = 'GET' | 'POST' | 'PUT' | 'DELETE'

class Http {


  get(url: string, data: object) {
    return this.commonHttp('GET', url, data)
  }

  post(url: string, data: object, contentType?: string) {
    return this.commonHttp('POST', url, data, contentType)
  }

  delete(url: string, data: object) {
    return this.commonHttp('DELETE', url, data)
  }

  put(url: string, data: object) {
    return this.commonHttp('PUT', url, data)
  }

  async commonHttp(method: HttpMethods, url: string, data: object, contentType?: string) {
    let token = Taro.getStorageSync("access_token")

    if (token) {
      token = "Bearer " + token
    }
    if (!contentType) {
      contentType = 'application/json'
    }

    url = SettingUtils.baseUrl + url
    return await Taro.request({
      url,
      method,
      data,
      header: {
        'content-type': contentType,
        'Authorization': token
      }
    })
  }
}

export default new Http()

